package com.nervenets.web.controller.ad;

import com.nervenets.web.controller.BaseController;
import com.nervenets.web.controller.IdTokenParams;
import com.nervenets.web.entity.KeyValue;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.entity.ResponseResult;
import com.nervenets.web.hibernate.dao.AdDao;
import com.nervenets.web.hibernate.domain.ad.Ad;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import javax.validation.ConstraintViolation;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Api(value = "广告类接口v1", description = "广告类接口")
@RestController
@RequestMapping("/api/v1/ad")
public class AdController extends BaseController {
    @Resource
    private AdDao adDao;

    @ApiOperation(value = "广告列表", response = Ad.class)
    @PostMapping("/list")
    public ResponseResult list(@RequestBody AdListPagingParams params) {
        final Set<ConstraintViolation<AdListPagingParams>> errors = validator.validate(params);
        if (!errors.isEmpty()) {
            return errorMessage(errors);
        }

        Specification<Ad> specification = (Specification<Ad>) (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (null != params.getAdType()) {
                predicates.add(criteriaBuilder.equal(root.get("adType"), params.getAdType()));
            }
            switch (params.getEnable()) {
                case -1:
                    predicates.add(criteriaBuilder.equal(root.get("enable"), false));
                    break;
                case 1:
                    predicates.add(criteriaBuilder.equal(root.get("enable"), true));
                    break;
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        final Page<Ad> pages = adDao.findAll(specification, PageRequest.of(params.getPage(), params.getLimit(), new Sort(Sort.Direction.DESC, "id")));
        List<Ad> ads = new ArrayList<>();
        pages.map(ad -> {
            ads.add(ad);
            return ad;
        });

        return successMessage(ads, new KeyValue("page", params.getPage()), new KeyValue("total", pages.getTotalElements()));
    }

    @ApiOperation(value = "广告详情", response = Ad.class)
    @PostMapping("/detail")
    public ResponseResult detail(@RequestBody IdTokenParams params) {
        final Set<ConstraintViolation<IdTokenParams>> errors = validator.validate(params);
        if (!errors.isEmpty()) {
            return errorMessage(errors);
        }

        Ad ad = adDao.findById(params.getTargetId()).orElse(null);
        if (null == ad) return errorMessage(MessageCode.code_404, "您要查看的广告不存在");

        return successMessage(ad);
    }

    @ApiOperation(value = "广告添加或编辑", response = Ad.class)
    @PostMapping("/edit")
    public ResponseResult edit(@RequestBody AdEditParams params) {
        final Set<ConstraintViolation<AdEditParams>> errors = validator.validate(params);
        if (!errors.isEmpty()) {
            return errorMessage(errors);
        }

        Ad ad = new Ad();
        if (params.getAdId() > 0) {
            ad = adDao.findById(params.getAdId()).orElse(null);
            if (null == ad) return errorMessage(MessageCode.code_404, "您编辑的广告不存在");
        }

        ad.setAdType(params.getAdType());
        ad.setTitle(params.getTitle());
        ad.setPicture(params.getPicture());
        ad.setUrl(params.getUrl());
        ad.setQueue(params.getQueue());
        ad.setEnable(params.isEnable());
        adDao.save(ad);

        return successMessage(ad);
    }

    @ApiOperation(value = "广告删除")
    @PostMapping("/del")
    public ResponseResult del(@RequestBody IdTokenParams params) {
        final Set<ConstraintViolation<IdTokenParams>> errors = validator.validate(params);
        if (!errors.isEmpty()) {
            return errorMessage(errors);
        }

        Ad ad = adDao.findById(params.getTargetId()).orElse(null);
        if (null == ad) return errorMessage(MessageCode.code_404, "您要删除的广告不存在");

        adDao.delete(ad);

        return successMessage();
    }
}
